<?php

@session_start();
include('ipnlistener.php');
include_once('inc/config.inc.php');

$associative_values = parse_ini_string(file_get_contents(dirname(DOCUMENT_ROOT) . '/application/application.ini'), true);
$db_host = $associative_values['database']['db_host'];
$db_user = $associative_values['database']['db_user'];
$db_name = $associative_values['database']['db_name'];
$db_password = $associative_values['database']['db_password'];

global $dbSingleton;
$dbSingleton = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name, $db_user, $db_password);

$listener = new IpnListener();
$listener->use_sandbox = true;

try {
    $verified = $listener->processIpn();
} catch (Exception $e) {
    // fatal error trying to process IPN.
    exit(0);
}

if ($verified) {
    // IPN response was "VERIFIED"
    $customValues = explode(';', $_POST['custom']);
    $contents .= 'application = ' . json_encode($associative_values);
    $contents .= 'post = ' . json_encode($_POST);
    $contents .= 'customValues = ' . json_encode($customValues);

    if (is_array($customValues) && count($customValues)) {
        $num_prestas = 0;
        $user_id = $customValues[0];
        unset($customValues[0]);
        foreach ($customValues as $id_payement_ok) {
            if (ctype_alnum(trim($id_payement_ok))) {
                $dbSingleton->query('UPDATE msa_slotobject SET paypal="1" WHERE event_id="' . $id_payement_ok . '"');
                $num_prestas++;
            }
        }
        // Insert into paypal table 
        $query = $dbSingleton->prepare('INSERT INTO paypal(user_id, num_prestas, time) VALUES(?, ?, ?)');
        $query->execute(array(trim($user_id), trim($user_id), time()));
    }
} else {
    // IPN response was "INVALID"
}
?>